package com.pig4cloud.pigx.common.security.grant.api;

import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * OpenApi鉴权Token
 *
 * @since 2022/11/7 17:49
 */
public class ApiAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = 1L;

    private final Object principal;

    /**
     * 授权类型
     */
    @Getter
    private String grantType;

    /**
     * 通行密钥
     */
    @Getter
    private String accessKey;

    /**
     * 全参构造函数
     *
     * @param accessKey 通行密钥
     * @param grantType 授权类型
     * @since 2022/11/7 17:50
     */
    public ApiAuthenticationToken(String accessKey, String grantType) {
        super(AuthorityUtils.NO_AUTHORITIES);
        this.principal = accessKey;
        this.accessKey = accessKey;
        this.grantType = grantType;
    }

    /**
     * 查询到用户信息后重新创建校验信息
     *
     * @param token   鉴权信息
     * @param sysUser 用户信息
     * @since 2023/3/2 10:03
     */
    public ApiAuthenticationToken(ApiAuthenticationToken token, UserDetails sysUser) {
        super(sysUser.getAuthorities());
        this.principal = sysUser;
        this.accessKey = token.getAccessKey();
        this.grantType = token.getGrantType();
        super.setAuthenticated(true); // 设置认证成功 必须
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public Object getCredentials() {
        return null;
    }
}
